import * as Request from '../request';
import { SuzhouDistrictMap } from '@config/map';
import { RankTOOL } from '@utils/index';

interface DATA {
  xAxisData: number[];
  seriesData: number[];
}

// 地图柱状图、区域排名数据
export const RegionTrendAPI = async (params) => {
  const url = '/api/company/analysis';
  let res: any = [];
  try {
    res = await Request.post(url, params);
  } catch (error) {
    console.log('request error:', url, error);
  }

  console.log(res, 'RegionTrendAPI');

  const rankedRes = RankTOOL(res.data, 'value');

  return SuzhouDistrictMap.map((d) => {
    const item = rankedRes.find((r: any) => r.name === d.name);
    d.value = item?.value ?? -1;
    d.rank = item?.rank;

    return d;
  });
};

// 企业数量统计
export const GetCompanyCntAPI = async (params) => {
  const url = '/api/company/analysis';
  let res: any;
  try {
    res = await Request.post(url, params);
  } catch (error) {
    console.log('request error:', url, error);
  }

  console.log(res?.data?.[0]?.value, 'GetCompanyCntAPI');
  return res?.data?.[0]?.value ?? '-';
};

// 企业增长趋势
export const IncreaseTrendAPI = async (params) => {
  const url = '/api/company/increase_trend';
  let res: any = [];
  try {
    res = await Request.post(url, params);
  } catch (error) {
    console.log('request error:', url, error);
  }

  const sortedRes = res?.data.sort((a, b) => a.name - b.name);
  const data: DATA = { xAxisData: [], seriesData: [] };

  sortedRes.forEach((r) => {
    data.seriesData.push(r.value);
    data.xAxisData.push(r.name);
  });

  return data;
};

// 专利增长趋势
export const PatentTrendAPI = async (params) => {
  const url = '/api/patent/increase_trend';
  let res: any = [];
  try {
    res = await Request.post(url, params);
  } catch (error) {
    console.log('request error:', url, error);
  }

  const sortedRes = res?.data.sort((a, b) => a.name - b.name);
  const data: DATA = { xAxisData: [], seriesData: [] };

  sortedRes.forEach((r) => {
    data.seriesData.push(r.value);
    data.xAxisData.push(r.name);
  });

  return data;
};

// 企业排名
export const CompanyRankAPI = async (params) => {
  const url = '/api/company';
  let res = { data: [{}], total: 0 };
  try {
    res = await Request.post(url, params);
  } catch (error) {
    console.log('request error:', url, error);
  }

  const data = res?.data;
  // 不足10个补到10个
  while (data.length < 10) {
    data.push({
      company_name: '-',
    });
  }
  return data;
};
